﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Net;
using System.ServiceModel;
using WordPressShared;

namespace WebCgiRoleWordPress
{
    public class WebRole : RoleEntryPoint
    {
        private ServiceHost host;
        public static string ImageStorePath;

      
        public override bool OnStart()
        {
            // Inits the Diagnostic Monitor
            //RoleStartupUtils.InitializeDiagnosticMonitor();     
            // Map the network drive
            try
            {
                StartWCFService();

                ImageStorePath = RoleEnvironment.GetConfigurationSettingValue("localPath");

                try
                {
                    // Indico al WordPress el path de Azure Drive
                    string strMyconfig = string.Format(@"<?php 
define('AZURE_DRIVE', '{0}');
?>", ImageStorePath.Replace("\\", "\\\\"));
                    FileStream strFichero = File.Create(string.Format("{0}\\approot\\myconfig.php", Environment.GetEnvironmentVariable("RoleRoot")));
                    byte[] arBytes = Encoding.ASCII.GetBytes(strMyconfig);
                    strFichero.Write(arBytes, 0, arBytes.Length);
                    strFichero.Flush();
                    strFichero.Close();
                }
                catch { }
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString(), "Error");
            }


            return base.OnStart();
        }

        public override void OnStop()
        {
            StopWCFService();
            base.OnStop();
        }

        private void StartWCFService()
        {
            try
            {
                IPEndPoint ipEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["SMBService"].IPEndpoint;
                host = new ServiceHost(typeof(SMBService));
                NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
                host.AddServiceEndpoint(typeof(ISMBService), binding, SMBService.GetUrlFormat(ipEndPoint));

                host.Open();
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message, "Error");
                throw;
            }
            Trace.WriteLine("WCF Hello service running...");
        }
        private void StopWCFService()
        {
            try
            {
                if (host != null && host.State == CommunicationState.Opened)
                    host.Close();
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Exception: " + ex.Message, "Information");
            }
        }
    }
}